package com.home.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.home.demo.dao.MenuAndRoleDao;
import com.home.demo.entity.MenuAndRoleEntity;
import com.home.demo.entity.dto.menuAndRole.MenuAndRoleDTO;
import com.home.demo.service.MenuAndRoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service("menuAndRoleService")
public class MenuAndRoleServiceImpl extends ServiceImpl<MenuAndRoleDao, MenuAndRoleEntity> implements MenuAndRoleService {


    /**
     * 保存角色与菜单的关联
     * @param menuAndRoleDTO
     */
    @Override
    public void saveInfo(MenuAndRoleDTO menuAndRoleDTO) {
        if (menuAndRoleDTO!=null&&menuAndRoleDTO.getMenuId()!=null){
            baseMapper
                    .delete(new QueryWrapper<MenuAndRoleEntity>()
                            .eq(StringUtils.hasText(menuAndRoleDTO.getRoleId())
                                    ,"role_id"
                                    ,menuAndRoleDTO.getRoleId()));

            List<MenuAndRoleEntity> collect = Arrays.stream(menuAndRoleDTO.getMenuId()).map(mId -> {
                MenuAndRoleEntity menuAndRoleEntity = new MenuAndRoleEntity();
                menuAndRoleEntity.setMenuId(mId);
                menuAndRoleEntity.setRoleId(menuAndRoleDTO.getRoleId());
                return menuAndRoleEntity;
            }).collect(Collectors.toList());

            this.saveBatch(collect);
        }
    }

    /**
     * 删除角色与菜单的关联
     * @param menuAndRoleDTO
     */
    @Override
    public void removeInfoByIds(MenuAndRoleDTO menuAndRoleDTO) {
        if (menuAndRoleDTO!=null&&menuAndRoleDTO.getMenuId()!=null){
            baseMapper
                    .delete(new QueryWrapper<MenuAndRoleEntity>()
                            .in("menu_id",menuAndRoleDTO)
                            .eq(StringUtils.hasText(menuAndRoleDTO.getRoleId()),"role_id",menuAndRoleDTO.getRoleId())
                    );

        }
    }
}